package com.bs.service;

import com.bs.domain.Partitions;
import com.bs.repository.PartitionsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wenguangjia on 2017/7/25.
 */
@Service
@Transactional
public class PartitionsService {
    @Autowired
    private PartitionsRepository partitionsRepository;

    public List<Partitions> getPartitionss(Partitions partitions){
        List<Partitions> list= partitionsRepository.findAll(where(partitions));
        return list;
    }

    public void save(Partitions partitions){
        partitionsRepository.save(partitions);
    }

    public void delete(Partitions partitions){
        partitionsRepository.delete(partitions);
    }
    /**
     * 条件查询时动态组装条件
     */
    private Specification<Partitions> where(Partitions partitions) {
        return new Specification<Partitions>() {
            @Override
            public Predicate toPredicate(Root<Partitions> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                //ename
                if (partitions.getEname() != null && !partitions.getEname().equals("")) {
                    predicates.add(cb.equal(root.<String>get("ename"), partitions.getEname()));
                }
                //cname
                if (partitions.getCname() != null && !partitions.getCname().equals("")) {
                    predicates.add(cb.equal(root.<String>get("cname"), partitions.getCname()));
                }
                //fname
                if (partitions.getFname() != null && !partitions.getFname().equals("")) {
                    predicates.add(cb.equal(root.<String>get("fname"), partitions.getFname()));
                }
//                if(partitions.getHostname() != null && !partitions.getHostname().equals("")){
//                    predicates.add(cb.equal(root.<String>get("hostname"),partitions.getHostname()));
//                }
                return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
            }
        };
    }
}
